//! 随机ID

use crate::{Id, IdKind, ID_LEN};
#[cfg(feature = "wasm")]
use wasm_bindgen::prelude::*;

#[cfg_attr(feature = "wasm", wasm_bindgen)]
#[derive(Debug, PartialEq)]
pub struct RandomId {
    len: usize,
    buf: [u8; ID_LEN],
}
#[cfg_attr(feature = "wasm", wasm_bindgen)]
impl RandomId {
    pub const fn new(sn: &[u8]) -> Self {
        let mut i_s = 0;
        while i_s < sn.len() - 1 && sn[i_s] == 0 {
            i_s += 1;
        }
        let sn_len = sn.len() - i_s;

        let mut buf = [0; ID_LEN];
        buf[0] = 0x40 | (sn_len as u8 - 1);
        let mut i = 0;
        while i < sn_len {
            buf[1 + i] = sn[i_s + i];
            i += 1;
        }
        return RandomId {
            len: 1 + sn_len,
            buf,
        };
    }
    pub const fn id(&self) -> Id {
        Id {
            len: self.len,
            buf: self.buf,
        }
    }
    pub fn try_from(id: &Id) -> Option<RandomId> {
        if id.kind() != IdKind::Random {
            return None;
        }
        return Some(RandomId {
            len: id.len,
            buf: id.buf,
        });
    }
}
